//
//  THSearchViewController.m
//  TreeHole
//
//  Created by apple on 2020/9/18.
//  Copyright © 2020 stoneobs. All rights reserved.
//

#import "THSearchViewController.h"

@interface THSearchViewController ()<UITextFieldDelegate>
@property(nonatomic, strong) UIView                     *header;/**<  */
@property(nonatomic, strong) NSMutableArray                   *dataSouce;/**<  */
@property(nonatomic, assign) NSInteger                     page;/**<  */
@property(nonatomic, strong) UICollectionView                     *collectionView;
@property(nonatomic, strong) STTools_SegementAutoView                     *segView;/**<  */
@property(nonatomic, strong) NSMutableArray<STButton*>                     *button_array;/**<  */
@property(nonatomic, assign) NSInteger                     current_index;/**<  */
@property(nonatomic, strong) UITextField                     *searchTextFiled;/**<  */
@end

@implementation THSearchViewController

- (void)stoneobs_fun_st_rightBarAction:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark --vc生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    [self stoneobs_fun_st_setRightItemWithTitle:@"取消" titleColor:STONEOBS_UI_THIRD_TEXT_COLOR];
    self.current_index = 0;
    self.view.backgroundColor = WH_UICOLOR_FROM_RGBA(0xFBFBFB);
    self.header = [self config_header_view];
    [self.view addSubview:self.header];
    [self.view addSubview:self.collectionView];
    [self.collectionView.mj_header beginRefreshing];
    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.didLoad) {
        [self sendHomeListRequest];
    }
    
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
- (UIView*)config_header_view{
    UITextField * textFiled = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, UISCREEN_WIDTH*0.7, 32)];
    textFiled.backgroundColor = WH_UICOLOR_FROM_RGBA(0xF1F1F6);
    self.navigationItem.titleView = textFiled;
    textFiled.layer.cornerRadius = 16;
    textFiled.clipsToBounds = YES;
    textFiled.placeholder = @"请输入关键字";
    textFiled.delegate = self;
    textFiled.clearButtonMode = UITextFieldViewModeAlways;
    textFiled.returnKeyType = UIReturnKeySearch;
    self.searchTextFiled = textFiled;
    
    STButton * stoneobs_ui_button = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 40, 32)
                                                              title:@""
                                                         titleColor:STONEOBS_UI_THIRD_TEXT_COLOR
                                                          titleFont:12
                                                       cornerRadius:16
                                                    backgroundColor:WH_UICOLOR_FROM_RGBA(0xF1F1F6)
                                                    backgroundImage:nil
                                                              image:ST_IMAGE_NAMED(@"搜索")];
    stoneobs_ui_button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [textFiled stoneobs_fun_setstoneobs_fun_st_leftView:stoneobs_ui_button];
    

    
    UIView * header = [UIView.alloc initWithFrame:CGRectMake(0, TMUtils.stoneobs_fun_get_navgationBarBootom, UISCREEN_WIDTH, 20)];
    __weak typeof(self) weakSelf =  self;
    
    //↑↓
    NSArray * array = @[@"销量",@"价格",@"上架时间"];
    self.segView = [[STTools_SegementAutoView alloc] initWithFrame:CGRectMake(15, 10, UISCREEN_WIDTH * 0.7, 50) andTitle:array handle:^(STTools_SegementAutoView *sender, UIButton *currentSelctedButton) {
        
        if (weakSelf.current_index == sender.cureentIndex) {
            NSInteger status = weakSelf.button_array[sender.cureentIndex].cus_slected_status;
            if (status == 0) {
                weakSelf.button_array[sender.cureentIndex].cus_slected_status = 1;
            }
            if (status == 1) {
                weakSelf.button_array[sender.cureentIndex].cus_slected_status = 2;
            }
            if (status == 2) {
                weakSelf.button_array[sender.cureentIndex].cus_slected_status = 1;
            }

        }else{
            for (STButton*button in weakSelf.button_array) {
                //↑↓
                button.cus_slected_status = 0;
            }
            weakSelf.button_array[sender.cureentIndex].cus_slected_status = 1;
        }
        
        for (STButton*button in weakSelf.button_array) {
            //↑↓
            NSInteger index = [weakSelf.button_array indexOfObject:button];
            if (button.cus_slected_status == 0) {
                [button setTitle:[NSString stringWithFormat:@"%@",array[index]] forState:UIControlStateNormal];
            }
            if (button.cus_slected_status == 1) {
                [button setTitle:[NSString stringWithFormat:@"%@↑",array[index]] forState:UIControlStateNormal];
            }
            if (button.cus_slected_status == 2) {
                [button setTitle:[NSString stringWithFormat:@"%@↓",array[index]] forState:UIControlStateNormal];
            }
        }
        
        weakSelf.current_index = sender.cureentIndex;
        [weakSelf.collectionView.mj_header beginRefreshing];
        
    }];
    self.button_array = self.segView.butArray;
    self.button_array.firstObject.cus_slected_status = 1;
    for (STButton*button in self.button_array) {
        //↑↓
        NSInteger index = [self.button_array indexOfObject:button];
        if (button.cus_slected_status == 0) {
            [button setTitle:[NSString stringWithFormat:@"%@",array[index]] forState:UIControlStateNormal];
        }
        if (button.cus_slected_status == 1) {
            [button setTitle:[NSString stringWithFormat:@"%@↑",array[index]] forState:UIControlStateNormal];
        }
        if (button.cus_slected_status == 2) {
            [button setTitle:[NSString stringWithFormat:@"%@↓",array[index]] forState:UIControlStateNormal];
        }
    }
    [header addSubview:self.segView];
    self.segView.lineSelectedColor = UIColor.clearColor;
    self.segView.lineSelectedView.backgroundColor = UIColor.clearColor;
    self.segView.lineColor = UIColor.clearColor;
    self.segView.autoMoveWithClic = YES;
    
    self.segView.butTitleSelectedColor = UIColor.blackColor;
    self.segView.butTitleColor = STONEOBS_UI_THIRD_TEXT_COLOR;
    self.segView.butTitleFont = [UIFont systemFontOfSize:15];
    self.segView.butTitleSelectedFont = [UIFont fontWithName:STONEOBS_UI_FONT_CU_NAME size:17];
    self.segView.butonWith  = 100;
    self.segView.left =  self.segView.left - 10;
    UIImageView * stoneobs_ui_imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 21, 10)];
    stoneobs_ui_imageView.image = [UIImage imageNamed:@"椭圆4"];
    [self.segView.lineSelectedView addSubview:stoneobs_ui_imageView];
    stoneobs_ui_imageView.centerX = self.segView.lineSelectedView.width/2;
    stoneobs_ui_imageView.centerY =  self.segView.lineSelectedView.height / 2;
    self.segView.lineSelectedView.clipsToBounds = NO;
    self.segView.lineSelectedView.top = self.segView.lineSelectedView.top-5;
    self.segView.clipsToBounds = NO;
    header.backgroundColor = UIColor.whiteColor;
    header.height = self.segView.bottom + 10 ;
    return header;
    
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if ([string isEqualToString:@"\n"]) {
        [self.collectionView.mj_header beginRefreshing];
        [self.searchTextFiled resignFirstResponder];
    }
    return YES;
}
- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout * flow = UICollectionViewFlowLayout.new;
        flow.sectionInset = UIEdgeInsetsMake(15, 15, 15, 15);
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, self.header.bottom, UISCREEN_WIDTH , TMUtils.stoneobs_fun_get_tabBarTop+49 - self.header.bottom) collectionViewLayout:flow];
        _collectionView.backgroundColor = UIColor.clearColor;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        //注册
        __weak typeof(self) weakSelf =  self;
        [_collectionView registerClass:[THGoodCollectionViewCell class] forCellWithReuseIdentifier:@"item"];
        _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            weakSelf.page = 1;
            [weakSelf sendHomeListRequest];
        }];

        _collectionView.st_noreslutView = [[STTools_NoresultView alloc] initWithFrame:CGRectMake(0, 50, UISCREEN_WIDTH, 400) title:@"暂无数据" buttonTitle:@"" buttonHandle:^(NSString *titleString) {
            
        }];

        self.automaticallyAdjustsScrollViewInsets = NO;
        if (STMC_IOS11) {
            if ([_collectionView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
                [_collectionView performSelector:@selector(setContentInsetAdjustmentBehavior:) withObject:@(2) afterDelay:0];
            }
        }else{
            self.automaticallyAdjustsScrollViewInsets = NO;
        }

    }
    return _collectionView;
}
#pragma --mark UICollectionViewDataSource
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataSouce.count;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat witdh =  (UISCREEN_WIDTH - 30 -  15)/2;
    return CGSizeMake(witdh, witdh + 65);
}
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    THGoodCollectionViewCell * item =[collectionView dequeueReusableCellWithReuseIdentifier:@"item" forIndexPath:indexPath];
    item.model = self.dataSouce[indexPath.row];
    item.layer.cornerRadius = 10;
    item.clipsToBounds = YES;
    return item;
}

#pragma --mark UICollectionViewDelegate
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
     THGoodModel* model = self.dataSouce[indexPath.row];
    [TMUtils goto_good_detail_witdh_id:model.g_id];
    [self.collectionView deselectItemAtIndexPath:indexPath animated:NO];
    
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat content = scrollView.contentOffset.y;
    //    NSLog(@"%0.2f",content);
}
#pragma mark --Action Method
- (void)onSelctedConditionButton{
    
}
#pragma mark --NetWork Method
- (void)configRefreshFooter{
    __weak typeof(self) weakSelf =  self;
    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.page ++;
        [weakSelf sendHomeListRequest];
    }];
}
- (void)sendHomeListRequest{
    NSMutableDictionary * stoneobs_net_param_dic = [NSMutableDictionary new];
    NSString * stoneobs_net_user_id = [STTools_UserManger defult].stoneobs_fun_get_loginedUser.uid.description;
    NSString * stoneobs_net_user_token = STTools_UserManger.defult.stoneobs_fun_get_loginedUser.token;
    if (stoneobs_net_user_id.length) {
        [stoneobs_net_param_dic setObject:stoneobs_net_user_id forKey:@"uid"];
    }
    if (stoneobs_net_user_token.length) {
        [stoneobs_net_param_dic setObject:stoneobs_net_user_token forKey:@"token"];
    }
    if (self.searchTextFiled.text.length) {
        [stoneobs_net_param_dic setObject:self.searchTextFiled.text forKey:@"name"];
    }
    NSInteger index = self.segView.cureentIndex;
    STButton * button = self.button_array[index];
    if (index == 0) {
        if (button.cus_slected_status == 2) {
            [stoneobs_net_param_dic setObject:@"sale_num_desc" forKey:@"sort"];
        }else{
            [stoneobs_net_param_dic setObject:@"sale_num" forKey:@"sort"];
        }
    }
    
    if (index == 1) {
        if (button.cus_slected_status == 2) {
            [stoneobs_net_param_dic setObject:@"price_desc" forKey:@"sort"];
        }else{
            [stoneobs_net_param_dic setObject:@"price" forKey:@"sort"];
        }
    }
    if (index == 2) {
        if (button.cus_slected_status == 2) {
            [stoneobs_net_param_dic setObject:@"created_at_desc" forKey:@"sort"];
        }else{
            [stoneobs_net_param_dic setObject:@"created_at" forKey:@"sort"];
        }
    }
    [stoneobs_net_param_dic setObject:@(self.page) forKey:@"page"];
    
    NSString * stoneobs_net_net_url = [NSString stringWithFormat:@"%@%@",RELEASE_SERVER_URL_HEADER,@"v1/goods/goodsList"];
    DDLogInfo(@"url:%@",stoneobs_net_net_url);
    DDLogInfo(@"param:%@",stoneobs_net_param_dic);
    [[STTools_NetWrokManger defaultClient] stoneobs_fun_requestWithPath:stoneobs_net_net_url
                                                                 method:STHttpRequestType_stoneobs_enumGet
                                                             parameters:stoneobs_net_param_dic
                                                                success:^(NSURLSessionDataTask *operation, id responseObject) {
        [SVProgressHUD dismiss];
        NSDictionary * dic = [responseObject valueForKey:@"data"];
        NSArray * array = dic[@"items"];
        NSArray * objArray = [THGoodModel mj_objectArrayWithKeyValuesArray:array];
        NSInteger total = [dic[@"total"] integerValue];//总数量
        CGFloat perPage = [dic[@"perPage"] floatValue];
        CGFloat allpage = total / perPage; ;
        if (self.page == 1) {
            self.dataSouce = objArray.mutableCopy;
            [self.collectionView reloadData];
            if (allpage>1) {
                [self configRefreshFooter];
            }
        }else{
            if (self.page < allpage) {
                [self.collectionView.mj_footer endRefreshing];
            }else{
                [self.collectionView.mj_footer endRefreshingWithNoMoreData];
            }
            [self.dataSouce addObjectsFromArray:objArray];
            [self.collectionView reloadData];
        }
        [self.collectionView.mj_header endRefreshing];
        
        
    } failure:^(NSString *stateCode, STTools_Error *error,NSError *originError) {
        [SVProgressHUD dismiss];
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
        DDLogError(@"\n请求失败:\nurl:%@\nparam:%@\n失败原因:%@\n错误码:%ld",
                   stoneobs_net_net_url,stoneobs_net_param_dic,error.desc,error.code);
    }];
    
}

@end
